package com.ctjsoft.competition;

/**
 * 测试使用同步关键字synchronized实现安全的买票
 *
 * @author liaoyy
 * @date Created in 2022/1/16 14:29
 */
public class TestSafeBuyTickets implements Runnable {

    /**
     * 总票数
     */
    private int num = 10;

    /**
     * 线程停止标识位
     */
    private boolean flag = true;

    @Override
    public void run() {
        while (flag){
            try {
                buyTickets();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        TestSafeBuyTickets testSafeBuyTickets = new TestSafeBuyTickets();
        new Thread(testSafeBuyTickets,"xiaowang").start();
        new Thread(testSafeBuyTickets,"xiaoli").start();
        new Thread(testSafeBuyTickets,"xiaochen").start();
    }

    synchronized void buyTickets() throws InterruptedException {
        if (num <= 0){
            flag = false;
            return;
        }
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName() + "买到了第" + num-- + "张票");
    }
}
